package com.weixing.mall.provider.support.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.weixing.mall.provider.model.domain.*;
import com.weixing.mall.provider.model.query.GoodsQuery;
import com.weixing.mall.provider.model.query.SpecValueQuery;
import com.weixing.mall.provider.model.vo.GoodsVo;
import com.weixing.mall.provider.model.vo.SpecValueVo;
import com.weixing.mall.provider.service.*;
import com.weixing.mall.util.ListUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class TestImportDataListener2 extends AnalysisEventListener<TestImportData2> {
    private static final Logger LOGGER = LoggerFactory.getLogger(TestImportData.class);
    @Autowired
    private IProductService productService;
    @Autowired
    private ISpecValueService specValueService;

    @Autowired
    private IGoodsService goodsService;
    /**
     * 每隔500条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;
    List<TestImportData2> list = new ArrayList<TestImportData2>();
    List<GoodsVo> goodList=Lists.newArrayList();
    List<SpecValueVo> colorList=Lists.newArrayList();
    List<SpecValueVo> sizeList=Lists.newArrayList();
    List<Product> productList=Lists.newArrayList();
    List<GoodsImg> goodsImgList=Lists.newArrayList();




    public TestImportDataListener2(ISpecValueService specValueService, IGoodsService goodsService,IProductService productService,IGoodsImgService goodsImgService) {
        this.goodsService = goodsService;
        this.specValueService=specValueService;
        this.productService=productService;
        GoodsQuery query=new GoodsQuery();
       this.goodList=goodsService.selectNoPage(query);
        SpecValueQuery specValueQuery=new SpecValueQuery();
        specValueQuery.setSpecId(1L);
        colorList=specValueService.selectList(specValueQuery);
        specValueQuery.setSpecId(2L);
        sizeList=specValueService.selectList(specValueQuery);
        productList=productService.list();
       // goodsImgList=goodsImgService.listAll();
    }


    @Override
    public void invoke(TestImportData2 data, AnalysisContext context) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        List<Product> productList=Lists.newArrayList();
        for(TestImportData2 data:list) {
            GoodsVo goodsVo = getGoodsBySn(data, goodList);
            if (null == goodsVo) {//写一个日志
                file("第"+data.getXh()+"货号为："+data.getGoodsSn()+"没有基础信息");
                continue;
            }

            String[] sizeArray = data.getSize().split(",");
            for (String ss : sizeArray) {
                Long[] skuArray = creatBySizeAndColor(data,ss, colorList, sizeList);
                if (null == skuArray) {//写一个日志
                    file("第"+data.getXh()+"货号为："+data.getGoodsSn()+"没有该颜色和尺码的基础信息");
                }else{//组装SKU数据
                    String [] skuAndSpace=creatSpecValue(data,skuArray,ss);
                    Product product=checkProduct(productList,skuAndSpace,goodsVo.getGoodsSn());
                    if(null==product){
                        product=new Product();
                        product.setDiscountPrice(new BigDecimal(goodsVo.getDiscountPrice()).setScale(2));
                        product.setMarketPrice(new BigDecimal(goodsVo.getMarketPrice()).setScale(2));
                        product.setSize(ss);
                        product.setColor(data.getColor().trim());
                        product.setStyleNo(goodsVo.getStyleNo());
                        product.setSupplierName(goodsVo.getSupplierName());
                        product.setProductSn(UUID.randomUUID().toString().replaceAll("-", ""));
                        product.setProductSku(skuAndSpace[1]);
                        product.setProductSkuDesp(skuAndSpace[0]);
                        String goodsImg=getGoodsImg(goodsVo.getId(),goodsImgList);
                        if(null==goodsImg){
                            file("第"+data.getXh()+"货号为："+data.getGoodsSn()+"没有维护货品图片，请在商品详情中进行维护");
                        }
                        product.setProductImg(goodsImg);
                        product.setCatName(goodsVo.getCatName());
                        product.setCreatedBy(1L);
                        product.setCreatedTime(goodsVo.getCreatedTime());
                        product.setCatId(goodsVo.getCatId());
                        product.setGoodsId(goodsVo.getId());
                        product.setGoodsSn(goodsVo.getGoodsSn());
                        product.setProductName(goodsVo.getGoodsName());
                        productList.add(product);

                    }else{//写个日志文件
                      //  file("第"+data.getXh()+"货号为："+data.getGoodsSn()+"该颜色和尺码信息已经存在");
                    }

                }
            }
        }
        productService.saveBatch(productList, ListUtil.SIZE);
        LOGGER.info("存储数据库成功！");
    }

    private String getGoodsImg(Long id,List<GoodsImg> imgList) {
        for(GoodsImg goodsImg:imgList){
            if(id.longValue()==goodsImg.getGoodsId().longValue()){
                return  goodsImg.getGoodsImg();
            }
        }
        return  null;
    }

    private String[] creatSpecValue(TestImportData2 data, Long[] skuArray,String ss) {
        String[]reslut=new String[2];
        reslut[0]=data.getColorSys()+":"+data.getColor()+","+data.getSizeSys()+":"+ss;
        reslut[1]=skuArray[0].toString()+":"+skuArray[1].toString()+","+skuArray[2].toString()+":"+skuArray[3].toString();
        return  reslut;
    }

    private Product checkProduct(List<Product> productList, String [] sku,String goodSn) {
       for(Product product:productList){
           if(product.getProductSkuDesp().equals(sku[0])&&product.getGoodsSn().equals(goodSn)){
               return  product;
           }
       }
       return null;
    }

    private Long[] creatBySizeAndColor(TestImportData2 data,String ss, List<SpecValueVo> colorList, List<SpecValueVo> sizeList) {
        Long[] result=new Long[4];
        for(SpecValueVo specValueVo:colorList){
            String colorSys=data.getColorSys().trim();
            String color=data.getColor().trim();
            if(colorSys.equals(specValueVo.getName())&&color.equals(specValueVo.getTwoName())){
                result[0]=specValueVo.getParentId();
                result[1]=specValueVo.getTwoId();
            }
        }
        for(SpecValueVo specValueVo:sizeList){
                String colorSys=data.getSizeSys().trim();
                String color=ss.trim();
                if(colorSys.equals(specValueVo.getName())&&color.equals(specValueVo.getTwoName())){
                    result[2]=specValueVo.getParentId();
                    result[3]=specValueVo.getTwoId();
            }
        }
        for(Long ll:result){
            if(null==ll){
                return  null;
            }
        }
        return  result;
    }

    private GoodsVo getGoodsBySn(TestImportData2 data, List<GoodsVo> goodList) {
        for(GoodsVo goodsVo: goodList){
            if(goodsVo.getGoodsSn().trim().equals(data.getGoodsSn().trim())){
                return  goodsVo;
            }
        }
        return  null;
    }
public  void file(String content){
    File f=new File("D:\\log.txt");
        FileWriter fw=null;
        BufferedWriter bw=null;
        try{
            if(!f.exists()){
                f.createNewFile();
            }
            fw=new FileWriter(f.getAbsoluteFile(),true);  //true表示可以追加新内容
            //fw=new FileWriter(f.getAbsoluteFile()); //表示不追加
            bw=new BufferedWriter(fw);
            bw.write(content+"\r\n");
            bw.close();
        }catch(Exception e){
            e.printStackTrace();
        }

}
    public static void main(String[] args) {

    }
}
